package com.jpz.serviceimp;

import com.jpz.bean.Role;
import com.jpz.bean.RolePermission;
import com.jpz.mapper.RoleMapper;
import com.jpz.mapper.RolePermissionMapper;
import com.jpz.service.RoleService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jpz
 * @since 2018-11-14
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
	@Autowired
	RoleMapper rm;

	@Autowired
	RolePermissionMapper rpm;


	@Override
	public boolean addRole(Role r, Integer[] menus_ids, Integer[] permission_ids) {
		Integer count = rm.insert(r); // 新增
		if (count > 0) {
			for (int i = 0; i < permission_ids.length; i++) {
				RolePermission rp = new RolePermission();
				rp.setSysRoleId(r.getId());
				rp.setSysPermissionId(permission_ids[i]);
				rpm.insert(rp);
			}
			for (int i = 0; i < menus_ids.length; i++) {
				RolePermission rp = new RolePermission();
				rp.setSysRoleId(r.getId());
				rp.setSysPermissionId(menus_ids[i]);
				rpm.insert(rp);
			}
			return true;
		}
		return false;
	}

	@Override
	public boolean updateRole(Role r, Integer[] menus_ids, Integer[] permission_ids) {
		Integer count = rm.updateById(r);
		if(count>0){
			rpm.delete(new EntityWrapper<RolePermission>().eq("sys_role_id", r.getId())); //清空
			for (int i = 0; i < permission_ids.length; i++) {
				RolePermission rp = new RolePermission();
				rp.setSysRoleId(r.getId());
				rp.setSysPermissionId(permission_ids[i]);
				rpm.insert(rp);
			}
			for (int i = 0; i < menus_ids.length; i++) {
				RolePermission rp = new RolePermission();
				rp.setSysRoleId(r.getId());
				rp.setSysPermissionId(menus_ids[i]);
				rpm.insert(rp);
			}
			return true;
		}
		return false;
	}

}
